<script setup lang="ts">
import { ref, onMounted } from "vue"
import BaseQuestion from "./base-question.vue"
import OptionItem from "./option-item.vue"
import { $t } from '@vben/locales';

defineOptions({ name: 'Radio' })

const props = defineProps<{
  modelValue: any
}>()
const emit = defineEmits(['update:modelValue'])
const optionsInit = [
  { name: 'A', content: '', file: '', path: '' },
  { name: 'B', content: '', file: '', path: '' },
  { name: 'C', content: '', file: '', path: '' },
  { name: 'D', content: '', file: '', path: '' },
]

const baseRef = ref()

const init = () => { }

onMounted(() => {
  // 确保数据类型正确
  if (typeof props.modelValue.answers !== 'string') {
    props.modelValue.answers = ''
  }
  // 只在选项为空时初始化，不要先清空
  if (!props.modelValue.options || props.modelValue.options.length === 0) {
    props.modelValue.options = [...optionsInit]
  }
})

const getData = async () => {
  return await baseRef.value?.getData()
}

const validate = () => {
  return baseRef.value?.validate()
}

const addOption = () => {
  const lastOption = props.modelValue.options[props.modelValue.options.length - 1]
  const lastChar = lastOption.name.charCodeAt(0)
  const newChar = String.fromCharCode(lastChar + 1)
  props.modelValue.options.push({
    name: newChar,
    content: '',
    file: '',
    path: ''
  })
}

const removeOption = (index: number) => {
  if (props.modelValue.options.length > 1) {
    props.modelValue.options.splice(index, 1)
    // 重新分配选项名称
    props.modelValue.options.forEach((option: any, idx: number) => {
      option.name = String.fromCharCode(65 + idx) // A, B, C, D...
    })
  }
}

defineExpose({
  init,
  getData,
  validate,
  baseRef
})
</script>

<template>
  <BaseQuestion ref="baseRef" :optionsInit="optionsInit" :modelValue="modelValue">
    <template #options>
      <el-form-item :label="$t('questionBank.questionOptions')" prop="options">
        <div class="w-full grid grid-cols-2 gap-4">
          <OptionItem v-for="(item, index) in modelValue.options" :key="index" v-model="modelValue.options[index]"
            :show-delete="index == modelValue.options.length - 1 && index != 0" :is-last="false"
            @upload="(options: any) => baseRef?.handleUpload(options.file, options.item)"
            @delete-image="baseRef?.delImg(item)" @delete="removeOption(index)" />
        </div>
        
          <!-- 新增选项按钮 -->
          <div class="mt-4">
            <el-button  plain @click="addOption">{{ $t('questionBank.addOption') }}</el-button>
          </div>
      </el-form-item>
    </template>
  </BaseQuestion>
</template>
